package com.headmaster.wap.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.headmaster.wap.util.WeixinConstant;
import com.headmaster.wap.util.WeixinUtils;

/**
 * 
 * @author suyujun
 * @date 2015年11月13日14:45:07
 * @description 微信相关请求处理类
 *
 */
@Controller
public class WeixinController {
	private static final Logger logger = Logger.getLogger(WeixinController.class);
	
	/**
	 * @author suyujun
	 * @date 2015年11月13日14:46:46
	 * @description 微信接入partnerpc token验证
	 * @param response
	 * @param signature 微信签名
	 * @param timestamp 时间戳
	 * @param nonce 随机数
	 * @param echostr 随机字符串
	 */
	@RequestMapping(value={"weixin/token/validAccessToken"},method=RequestMethod.GET)
	public void validAccessToken(HttpServletResponse response,
			@RequestParam(value = "signature", required = true) String signature,
			@RequestParam(value = "timestamp", required = true) String timestamp,
			@RequestParam(value = "nonce", required = true) String nonce,
			@RequestParam(value = "echostr", required = true) String echostr) {
		PrintWriter writer = null;
		try {
			logger.info("蘑菇公寓公众号接入网站验证！！");
			logger.info("signature=" + signature + " timestamp=" + timestamp + " nonce=" + nonce + " echostr=" + echostr);
			Object[] params = {WeixinConstant.TOKEN,timestamp,nonce};
			String sign = WeixinUtils.createSignature(params);
			logger.info("sign=" + sign);
			writer = response.getWriter();
			if(signature.equals(sign)){
				writer.print(echostr);			
			}else{
				writer.print("error");
			}
			writer.flush();
		} catch (IOException e) {
			logger.info("蘑菇公寓公众号接入网站异常！！" + e.getMessage());
			e.printStackTrace();
		} finally{
			if(writer != null){
				writer.close();
			}
		}
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value={"weixin/token/validAccessToken"},method=RequestMethod.POST,produces = "application/xml;charset=UTF-8")
	@ResponseBody
	public String processMsgFromWeixin(HttpServletRequest request,HttpServletResponse response){
		String respMessage = "";
        try {
			// 将请求、响应的编码均设置为UTF-8（防止中文乱码）  
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			logger.info("接收服务器端推送过来的消息");
//			InputStream inputStream = request.getInputStream();
//			String postData = IOUtils.toString(inputStream, "UTF-8");
//			logger.info(postData);
//			respMessage = userWeixinFacade.processRequest(request);			
		} catch (Exception e) {
			logger.error("",e);
			return null;
		} 
        return respMessage;
	}
}
